﻿using System;
using System.ComponentModel;
using Castle.ActiveRecord;
using Light.Framework.Contract;
using Light.Framework.Model;
using Light.Utility;
using Light.Weixin.Contract;
using Light.Framework.Castle;

namespace Light.Weixin.Model
{
    /// <summary>
    /// 微信应用
    /// </summary>
    [Traceable]
    [DisplayName("微信公众号")]
    [ActiveRecord]
    [ImportField]
    public class WxApp : Entity, IDefaultable
    {
        /// <summary>
        /// 扫码公众号二维码
        /// </summary>
        public event WxEventHandler OnQRScaned;

        /// <summary>
        /// 用户关注
        /// </summary>
        public event WxEventHandler OnSubscribed;

        /// <summary>
        /// 点击菜单：关键字
        /// </summary>
        public event WxEventHandler OnClicked;

        /// <summary>
        /// 收到输入文字消息
        /// </summary>
        public event WxEventHandler OnInputed;

        /// <summary>
        /// 处理接收到的消息
        /// </summary>
        /// <param name="msg"></param>
        public void ProcessMsg(WxMsg msg)
        {
            msg.Answer = msg.GetAnswer();

            if (msg.MsgType != WxMsgType.Unsubscribe)
                msg.FromUser = this.GetAndSaveUser(msg.FromUserName);

            if (msg.MsgType == WxMsgType.Scan && OnQRScaned != null)
            {
                OnQRScaned(this, msg);
            }
            else if (msg.MsgType == WxMsgType.Subscribe && OnSubscribed != null)
            {
                OnSubscribed(this, msg);
            }
            else if (msg.MsgType == WxMsgType.Text && OnInputed != null)
            {
                OnInputed(this, msg);
            }
            else if (msg.MsgType == WxMsgType.Click && OnClicked != null)
            {
                OnClicked(this, msg);
            }

            if (!String.IsNullOrEmpty(msg.Answer))
            {
                msg.MsgType = WxMsgType.Text;
                WebHelper.CurContext.Response.Write(msg.ToResponseXml());
                WebHelper.CurContext.Response.End();
            }
            else
            {
                this.SendMsgToAdmins(msg);

                WebHelper.CurContext.Response.Write("success");
                WebHelper.CurContext.Response.End();
            }
        }

        /// <summary>
        /// 应用类型
        /// </summary>
        [Property("FType")]
        public WxAppType Type { get; set; }

        [JsonSerialize("WxAppID")]
        public override int ID
        {
            get
            {
                return base.ID;
            }
            set
            {
                base.ID = value;
            }
        }

        /// <summary>
        /// 权限名称
        /// </summary>
        [Property("FName")]
        [Searchable("名称")]
        [JsonSerialize("WxAppName")]
        [ImportField("名称")]
        public string Name { get; set; }

        /// <summary>
        /// 原始ID
        /// </summary>
        [Property]
        [ImportField("原始ID")]
        public string OriginalID { get; set; }

        /// <summary>
        /// AppId
        /// </summary>
        [Property]
        [Searchable("AppID")]
        [ImportField("AppID")]
        public string AppID { get; set; }

        /// <summary>
        /// AppSecret
        /// </summary>
        [Property]
        [ImportField("AppSecret")]
        public string AppSecret { get; set; }

        /// <summary>
        /// 授权回调地址
        /// </summary>
        [Property]
        [ImportField("授权回调地址")]
        public string ReturnURL { get; set; }


        /// <summary>
        /// 授权回调地址
        /// </summary>
        [Property]
        [ImportField("服务器token令牌")]
        public string ServerToken { get; set; }

        /// <summary>
        /// 管理员账号OpenIDs多个以逗号“,”隔开
        /// 可用来接收系统通知
        /// </summary>
        [Property]
        [ImportField("管理员")]
        public string AdminOpenIDs { get; set; }

        /// <summary>
        /// 是否为默认
        /// </summary>
        [Property]
        public bool IsDefault { get; set; }

        /// <summary>
        /// 网页授权access_token（未保存至DB）
        /// </summary>
        public string AccessToken { get; set; }

        /// <summary>
        /// 网页授权openid（未保存至DB）
        /// </summary>
        public string OpenID { get; set; }

        protected override void ValidateRules()
        {
            base.AddValidateRules(!String.IsNullOrEmpty(AppID), "AppId不能为空");
            base.AddValidateRules(!String.IsNullOrEmpty(AppSecret), "AppSecret不能为空");
        }

        public override bool Equals(object obj)
        {
            WxApp app = obj as WxApp;
            if (app != null)
                return app.AppID == AppID;
            else
                return false;
        }

        public override string ToString()
        {
            return Name + " " + OriginalID;
        }

        /// <summary>
        /// 未知消息，转发给管理员处理
        /// </summary>
        /// <param name="msg"></param>
        private void SendMsgToAdmins(WxMsg msg)
        {

            if (msg.MsgType == WxMsgType.TemplateSendJobFinish ||
                msg.MsgType == WxMsgType.Click ||
                msg.MsgType == WxMsgType.Location ||
                msg.MsgType == WxMsgType.View ||
                msg.MsgType == WxMsgType.Scan ||
                msg.MsgType == WxMsgType.Unsubscribe)
            {
                //此类消息不通知管理员
                return;
            }

            using (new GuestUser())
            {
                IWxMsgComponent compMsg = ServerApplication.ComponentFactory.Create<IWxMsgComponent>();
                msg.WxApp = this;
                msg.Organization = this.Organization;
                msg.UserInfo = this.GetAndSaveUser(msg.FromUserName);
                compMsg.Save(msg);
            }

            if (msg.MsgType != WxMsgType.Text)
            {
                Light.Weixin.WxAppHelper.SendCusMsgToAdmins(msg);
            }

            WxTplMsg msgUnknow = new WxTplMsg();
            msgUnknow.FirstWords = "收到 " + EnumHelper.GetEnumDesc(msg.MsgType) + " 消息";
            msgUnknow.Remark = "点击进行回复";
            string wxMsgUrl = ApplicationSetting.ReadAppSetting("WxMsgUrl", "http://182918.com/Wap/WxMsg.aspx");
            msgUnknow.DetailUrl = wxMsgUrl + "?id=" + msg.ID;
            WxMsgTpl tpl = this.GetMsgTpl("asking");
            this.SendTplMsgToAdmins<WxMsg>(msgUnknow, tpl, msg);
        }
    }

}
